package com.atmilan.quartz.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.model.dto.jky.JkyProductSkuResDTO;
import com.atmilan.quartz.model.entity.crmeb.StoreProduct;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttrValue;
import com.atmilan.quartz.service.IStoreProductAttrValueService;
import com.atmilan.quartz.service.IStoreProductService;
import com.atmilan.quartz.utils.XxlJobParamUtil;
import com.atmilan.quartz.utils.product.JkyProductUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 吉客云商品数量同步
 */
@Slf4j
@Component
@Configuration
@EnableScheduling
public class JkyStockSyncTask {

    @Resource
    private IStoreProductService storeProductService;
    @Resource
    private IStoreProductAttrValueService storeProductAttrValueService;

    private volatile boolean run = false;


    /*@PostConstruct
    public void init() {
        syncTask();
    }*/


    @XxlJob("jkyStockSyncTask")
    public void syncTask() {
        log.info("吉客云商品数量同步任务开始");
        if (run) {
            log.warn("吉客云商品数量同步任务 正在运行中...");
        }
        try {
            run = true;
            Map<String, String> params = XxlJobParamUtil.getParams();
            Integer intervalOfHour = XxlJobParamUtil.getInteger(params, "intervalOfHour", 1);
            String warehouseCodes = XxlJobParamUtil.getAndCheckParam(params, "warehouseCode");
            if (StrUtil.isEmpty(warehouseCodes)) {
                syncByWarehouseCode(null, intervalOfHour);
            } else {
                List<String> warehouseCodeList = StrUtil.splitTrim(warehouseCodes, ',');
                for (String warehouseCode : warehouseCodeList) {
                    syncByWarehouseCode(warehouseCode, intervalOfHour);
                }
            }
            XxlJobHelper.handleSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            XxlJobHelper.log(e);
            XxlJobHelper.handleFail();
        } finally {
            run = false;
        }
        log.info("吉客云商品数量同步任务结束");
    }

    private String getBarCode(JkyProductSkuResDTO.GoodsStockQuantity goodsStockQuantity) {
        String barCode = BarCodeEnum.JKY.getCode() + goodsStockQuantity.getGoodsNo().toString();
        barCode += "-" + goodsStockQuantity.getWarehouseCode();
        if (!"tfx".equals(goodsStockQuantity.getWarehouseCode())) {
            if (StrUtil.isNotEmpty(goodsStockQuantity.getSkuName())) {
                String colorName = goodsStockQuantity.getSkuName().split(";")[0];
                if (StrUtil.isNotEmpty(colorName)) {
                    barCode += "-" + colorName;
                }
            }
        }
        /*if(!"tfx".equals(goodsStockQuantity.getWarehouseCode())) {
            barCode += "-" + goodsStockQuantity.getColorCode();
        }*/
        return barCode;
    }

    private String getSkuBarCode(JkyProductSkuResDTO.GoodsStockQuantity goodsStockQuantity) {
        return ProductTypeEnum.JKY.getCode() + "-" + goodsStockQuantity.getSkuBarcode().toString();
    }

    private String getSkuBarCode(StoreProductAttrValue sku) {
        return sku.getSourceSkuId();
    }

    public void syncByWarehouseCode(String warehouseCode, Integer intervalOfHour) throws Exception {
        Integer pageIndex = 0;
        Integer pageSize = 50;
        JkyProductSkuResDTO resultDto;
        Date now = new Date();
        do {
            resultDto = JkyProductUtil.pageJkyBatchSkus(pageIndex, pageSize, warehouseCode, intervalOfHour, now);
            if (null == resultDto) break;
            List<JkyProductSkuResDTO.GoodsStockQuantity> skus = resultDto.getResult().getDataResult().getGoodsStockQuantity();
            if (CollUtil.isEmpty(skus)) break;
            log.info("获取的原始数据:{}", skus);
            Map<String, Map<String, JkyProductSkuResDTO.GoodsStockQuantity>> skuMap = new HashMap<>();
            skus.forEach(d -> {
                if (StrUtil.isEmpty(d.getSkuBarcode())) return;
                String barCode = getBarCode(d);
                Map<String, JkyProductSkuResDTO.GoodsStockQuantity> map = skuMap.get(barCode);
                if (null == map) {
                    map = new HashMap<>();
                    skuMap.put(barCode, map);
                }
                map.put(getSkuBarCode(d), d);
            });
            for (Map.Entry<String, Map<String, JkyProductSkuResDTO.GoodsStockQuantity>> e : skuMap.entrySet()) {
                StoreProduct storeProduct = storeProductService.getByBarCode(e.getKey(), null, null);
                if (null == storeProduct) {
                    XxlJobHelper.log("contextId:" + resultDto.getResult().getContextId() + ",条码:" + e.getKey() + ",无法获取主表商品信息");
                    continue;
                } else {
                    XxlJobHelper.log("contextId:" + resultDto.getResult().getContextId() + ",条码:" + e.getKey() + ",获取到主表商品信息");
                }
                List<StoreProductAttrValue> skuList = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(
                        StoreProductAttrValue::getProductId, storeProduct.getId()
                ));
                int stock = 0;
                for (StoreProductAttrValue sku : skuList) {
                    JkyProductSkuResDTO.GoodsStockQuantity goodsStockQuantity = e.getValue().get(getSkuBarCode(sku));
                    if (null == goodsStockQuantity) {
                        stock += sku.getStock();
                        continue;
                    }
                    int oldStock = sku.getStock();
                    sku.setStock(new BigDecimal(goodsStockQuantity.getCurrentQuantity()).intValue());
                    stock += sku.getStock();
                    if (oldStock != sku.getStock()) {
                        storeProductAttrValueService.update(Wrappers.<StoreProductAttrValue>lambdaUpdate()
                                .eq(StoreProductAttrValue::getProductId, sku.getProductId())
                                .eq(StoreProductAttrValue::getSourceSkuId, sku.getSourceSkuId())
                                .set(StoreProductAttrValue::getStock, sku.getStock()));
                    }
                }
                if (stock != storeProduct.getStock()) {
                    storeProduct.setStock(stock);
                    storeProduct.setIsShow(stock == 0 ? Boolean.FALSE : Boolean.TRUE);
                    storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                            .eq(StoreProduct::getId, storeProduct.getId())
                            .set(StoreProduct::getStock, storeProduct.getStock())
                            .set(StoreProduct::getIsDel, false)
                            .set(StoreProduct::getIsShow, storeProduct.getIsShow()));
                    XxlJobHelper.log("商品:" + storeProduct.getStoreName() + ",编码:" + storeProduct.getBarCode());
                }
            }
            pageIndex++;
        } while (resultDto != null);
    }
}
